import router from './router'
import axios from "axios"
import store from './store/index'; 
import { generateIndexRouter } from "@/views/utils/util"

router.beforeEach((to, from, next) => {
   //  console.log(to);
   //  console.log(from);
   //  console.log(next);
   // 如果访问的首页直接放行
   if (to.path === '/login' || to.path === '/register') return next();


   // 获取tokens
   let tokenStr = JSON.parse(window.sessionStorage.getItem('Authorization'));
   console.log(tokenStr);

  if(!tokenStr){
     next({path: "/login"});
  }else

  if(true){
     console.log(".......")
       axios.get('/sys-menu/ListMenu_role_id?id='+tokenStr.id).then((resp) => {
        const  menuData=resp.data.result;
         if (menuData === null || menuData === "" || menuData === undefined) {
         return;
        };
        window.sessionStorage.setItem("menuInfo",JSON.stringify(menuData));
       let constRoutes = [];
       constRoutes = generateIndexRouter(menuData);

       router.options.routes=null; //动态添加路由
      // router.options.routes=constRoutes;
  

       router.addRoutes(constRoutes);
       router.options.routes = constRoutes;
       window.sessionStorage.setItem('AaddRouters',JSON.stringify(constRoutes));
 

       const redirect = decodeURIComponent(from.query.redirect || to.path)

       if (to.path === redirect) {
        next({ ...to, replace: true })
       } else {
        // 跳转到目的路由
        next({ path: redirect })
       }


    }).catch((ex) => {
     console.log(ex)
   });
}
//    else
   // // 没有token放回登录界面
   // if (!tokenStr) return next('/login');
   // // 有token放行
   return next()
}
);



axios.interceptors.request.use((config) => {
   config.headers.Authorization = window.sessionStorage.getItem('Authorization');
   return config
});